package com.gsm.service.impl;

import com.gsm.config.MyException;
import com.gsm.dao.LoginDao;
import com.gsm.dao.RegisterDao;
import com.gsm.dto.LoginUserDto;
import com.gsm.entity.RespCode;
import com.gsm.po.WebUser;
import com.gsm.service.LoginService;
import com.gsm.utils.CheckUtils;
import com.gsm.utils.JwtUtils;
import com.gsm.vo.LoginUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private LoginDao loginDao;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private RegisterDao registerDao;

    @Override
    public LoginUserVo selectUserInfo(LoginUserDto dto) {
        //校验账户名一定是手机号或者邮箱
        boolean b = CheckUtils.checkStrIsIphoneNo(dto.getAccount());
        boolean b1 = CheckUtils.checkStrIsEmail(dto.getAccount());
        if(!b && !b1){
            throw new MyException(RespCode.LOGIN_NAME_IS_NOT_IPHONE_NO_OR_EMAIL);
        }
        WebUser webUser = loginDao.selectWebUserByAccount(dto.getAccount());
        if (webUser == null) {
            throw new MyException(RespCode.REG_NAME_NOT_EXIST_ERROR);
        }
        //判断密码是否相同
        String pc = dto.getPc();
        String pc1 = webUser.getPc();
        Boolean bool = passwordEncoder.matches(pc, pc1);
        if(!bool){
            throw new MyException(RespCode.LOGIN_NAME_OR_PWD_ERROR);
        }
        webUser.setPo(null);
        webUser.setPc(null);
        //查询用户会员等级
        //TODO
        //生成Token
        String token = jwtUtils.getJwt(webUser.getWebUserId().toString(), webUser.getUserName(), null);
        //封装返回
        LoginUserVo loginUserVo = LoginUserVo.builder()
                .token(token)
                .webUser(webUser)
                .build();
        return loginUserVo;
    }

    @Override
    public LoginUserVo selectUserInfoByIphoneNo(String iphoneNo) {
        WebUser webUser = registerDao.selectUserByIphoneNo(iphoneNo);
        if (webUser == null) {
            throw new MyException(RespCode.REG_NAME_NOT_EXIST_ERROR);
        }
        webUser.setPo(null);
        webUser.setPc(null);
        //查询用户会员等级
        //TODO
        //生成Token
        String token = jwtUtils.getJwt(webUser.getWebUserId().toString(), webUser.getUserName(), null);
        //封装返回
        LoginUserVo loginUserVo = LoginUserVo.builder()
                .token(token)
                .webUser(webUser)
                .build();
        return loginUserVo;
    }

    @Override
    public boolean selectIphoneNoIsExist(String iphoneNo) {
        WebUser webUser = registerDao.selectUserByIphoneNo(iphoneNo);
        if (webUser != null) {
            return true;
        }
        return false;
    }
}
